﻿using System.ComponentModel.DataAnnotations;
using TodoApi.Models;

namespace TodoApi.Validationattributes
{
    public class StudentNameAttribute : ValidationAttribute
    {
        protected override ValidationResult? IsValid(object? value, ValidationContext validationContext)
        {
            //取数据库资料
            StudentContext studnets = (StudentContext)validationContext.GetServices(typeof(StudentContext));
            if(value == null)
            {
                return new ValidationResult("名字不能为空");
            }
            else
            {
                var student = studnets.Student.Where(x => x.Name.Contains(value.ToString()));
                if (student.Count() > 0)
                {
                    return new ValidationResult("名字已存在");
                }else
                {
                    return ValidationResult.Success;
                }
            }
        }
    }
}
